package com.unicom.office.var;

import com.unicom.office.dataitem.DataItem;
import com.unicom.office.dataitem.ListDataItem;
import com.unicom.office.type.*;

import java.util.*;

public class ListVarItem extends VarItem {
    // 当前数组元素的类型
    private TypeItem typeItem;
    // 当前数组的类型
    private TypeItem itemType;

    public ListVarItem(String name, TypeItem itemType) {
        super(name);
        this.itemType = itemType;
        typeItem = new ListTypeItem(null, itemType);
//        if(itemType instanceof ObjectTypeItem) {
//            // 其实，formatValue应该放在type中，而不是var中，下面的问题就解决了
//            this.itemType = new ObjectVarItem(null, (ObjectTypeItem) typeItem);
//        }else if(typeItem instanceof ListTypeItem) {
//            this.itemType = new ListVarItem(null, ((ListTypeItem) typeItem).getItemType());
//        }else if(typeItem instanceof StringTypeItem) {
//            this.itemType = new StringVarItem(null);
//        }else if(typeItem instanceof NumberTypeItem) {
//            this.itemType = new NumberVarItem(null);
//        }else {
//            throw new RuntimeException("暂不支持的数据类型");
//        }
        this.setDefaultValue(new ArrayList<Object>());
    }

    public TypeItem getTypeItem() {
        return typeItem;
    }

    public Object getFormatedValue(Object value) {
        List<Object> list = null;
        if(value == null){
            list = (List<Object>)getDefaultValue();
        }else if(value instanceof String){
            String str = (String)value;
            if(str.charAt(0) == '['){
                String[] split = str.substring(1, str.length() - 1).split(",");
                list = new ArrayList<Object>();
                for (String s : split) {
                    list.add(s.trim());
                }
            }else{
                throw new RuntimeException("字符串不能转为数组");
            }
        }else if(value instanceof List){
            list = (List<Object>)value;
        }else {
            throw new RuntimeException("值类型错误");
        }

        // 对象的数据需要把属性也格式化
        List<Object> result = new ArrayList<Object>();
        for (Object item : list) {
            Object temp = itemType.createVarItem(null).getFormatedValue(item);
            result.add(temp);
        }

        return result;
    }

    public DataItem createDataItem(Object value) {
        return new ListDataItem(value, this);
    }

    public TypeItem getItemType() {
        return itemType;
    }
}
